"use strict";

const Service = require("egg").Service;
const { hash, compare } = require("../utils/password");

class UsersService extends Service {
  async index() {
    const { ctx } = this;
    // Fetch all users from the database
    const users = await ctx.model.User.findAll({
      attributes: ["id", "username", "email", "createdAt", "updatedAt"],
      order: [["createdAt", "DESC"]],
    });
    // Return the list of users
    return users;
  }

  async create(params) {
    const { ctx } = this;

    // Validate the user data
    ctx.validate(
      {
        username: { type: "string", required: true, allowEmpty: false },
        password: { type: "string", required: true, allowEmpty: false },
        email: {
          type: "string",
          required: true,
          allowEmpty: false,
          format: /\S+@\S+\.\S+/,
        },
      },
      params
    );

    params.password = await hash(params.password);
    // Create the user
    const result = await ctx.model.User.create(params);

    // Return the created user
    return result;
  }

  async login(params) {
    const { ctx, app } = this;

    const user = await ctx.model.User.findOne({
      where: { username: params.username },
    });

    if (!user) {
      ctx.throw(401, "用户名或密码错误");
    }
    // 验证密码
    const isValid = await compare(params.password, user.password);
    if (!isValid) {
      ctx.throw(401, "用户名或密码错误");
    }

    // Return the authenticated user
    user.password = undefined; // 不返回密码
    return user;
  }
}

module.exports = UsersService;
